package com.servlet;


import com.model.Manage;
import com.service.ManageService;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet( "/ManageServlet")
public class ManageServlet extends HttpServlet {
    ManageService ms = new ManageService();
    HttpServletRequest request;
    HttpServletResponse response;
    protected void doGet (HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,IOException {
        //接受页面的判断me,判断当前方法执行什么内容
        this.request=request;
        this.response=response;
        String me = request.getParameter("method");
        if(me.equals("show")){
            this.show();
        }
        //添加数据
        if (me.equals("add")){
            this.add();
        }
        //删除数据
        if (me.equals("delete")){
            this.delete();
        }
        //修改数据
        if (me.equals("toupdate")){
            this.toupdate();
        }
        if (me.equals("update")){
            this.update();
        }

    }


    private void update() throws IOException {
        String uid=request.getParameter("uid");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        ms.update(uid,username,password);
        //response  对象向页面响应
        //response.getWriter().print("<script>parent.showStudent()</script>");
    }

    private void toupdate() throws ServletException, IOException {
        String id = request.getParameter("id");
        Manage manage= ms.toupdate(id);
        request.setAttribute("manage",manage);
        request.getRequestDispatcher("jsp/manage/update.jsp").forward(request,response);
    }

    private void delete() throws ServletException, IOException {
        String id=request.getParameter("id");
        ms.delete(id);
        this.show();
    }

    private void add() throws IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        ms.add(username,password);
//        //response  对象向页面响应
        //response.getWriter().print("<script>parent.showStudent()</script>");
    }

    private void show() throws ServletException, IOException {
        //从service中获取集合数据为db中的
        List<Manage> manages = ms.show();
        //将数据传递给页面
        request.setAttribute("manages",manages);
        //跳转到指定的页面
        request.getRequestDispatcher("jsp/manage/show.jsp").forward(request,response);
    }
}

